#sem:name: Java applet
#sem:tip: Generates a web applet in java (requires java)
#sem:picture

# Thomas Nagy, 2007-2015

import os, shutil, time, sys

# TODO for the moment it does not work

outdir = sembind.get_var('outdir')+'/'+sembind.get_var('pname')

try:
	tm = time.strftime('.%d-%b-%y--%H-%M-%S', time.gmtime(os.stat(outdir).st_mtime))
	os.rename(outdir, outdir+tm)
except OSError:
	pass

try:
	os.makedirs(outdir)
except OSError:
	sys.stderr.write("Cannot create folder " + outdir)

try:
	os.makedirs(outdir + '/pics')
except OSError:
	sys.stderr.write("Cannot create the pics folder in %s" % outdir)

for x in "Makefile main.html Kadapplet.java Mapview.java".split():
	shutil.copy2(template_dir() + '/java/'+x, outdir)

cwd = os.getcwd()
os.chdir(sembind.get_var('temp_dir'))
pics = {} # map the id to the picture
lst = os.listdir('.')
for x in lst:
	if x.startswith('diag-') or x.startswith('wholemap'):
		pics[ x.replace('diag-', '').split('.')[0] ] = x
		shutil.copy2(x, outdir + '/pics')
os.chdir(cwd)

code = []
def out(s):
	global code
	code.append(s)

def low_coords(node):
	x = float(node.get_val('x'))
	y = float(node.get_val('y'))

	num = node.child_count()
	for i in range(num):
		x2, y2 = low_coords(node.child_num(i))
		if x2 < x:
			x = x2
		if y2 < y:
			y = y2
	return (x, y)

def print_rec(node, X, Y):
	x = float(node.get_val('x')) - X
	y = float(node.get_val('y')) - Y
	w = float(node.get_val('w'))
	h = float(node.get_val('h'))

	if node.get_val('type') == 'text':
		txt = node.get_val('text')
		txt = clear_html(txt)
		txt = repr(txt)[1:-1].replace('"', '\\"')

		s = '\nif (x > %f && y > %f && x < %f && y < %f) { return "%s"; }\n' % (x, y, x+w, y+w, txt)
		out(s)

	num = node.child_count()
	for i in range(num):
		print_rec(node.child_num(i), X, Y)

root = Root()
x, y = low_coords(root)

out("/** Generated by Semantik */\n\n")
out("public class TextCoord\n{\n")
out("public static String coordToText(double x, double y) {\n")
print_rec(root, x - 25, y - 25)
out("return \"\";\n")
out("}\n}\n")

file = open(outdir+'/TextCoord.java', 'w')
try:
	file.write(''.join(code))
finally:
	file.close()


